package com.origin.niuke.dfs;

import java.util.ArrayList;
import java.util.List;

/**
 * NC232 加起来和为目标值的组合(三)
 * 算法：回溯
 *
 * @author yezh
 * @date 2022/12/10 17:37
 */
public class NC232 {

    List<List<Integer>> list;

    public int[][] combination(int k, int n) {
        // write code here
        list = new ArrayList<>();
        dfs(new ArrayList<>(), 1, n, k);
        int[][] ans = new int[list.size()][k];
        for (int i = 0; i < list.size(); i++)
            for (int j = 0; j < k; j++) ans[i][j] = list.get(i).get(j);
        return ans;
    }

    void dfs(List<Integer> cur, int start, int target, int k) {
        if (cur.size() == k) {
            if (target == 0) list.add(new ArrayList<>(cur));
            return;
        }
        for (int i = start; i <= 9; i++) {
            if (start > target) break;
            cur.add(i);
            dfs(cur, i + 1, target - i, k);
            cur.remove(cur.size() - 1);
        }
    }

}
